/*
 * @Author: your name
 * @Date: 2021-02-24 18:12:21
 * @LastEditTime: 2021-03-02 16:47:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \xgwsp_frontendd:\project\tsx\demo-tsx\src\hooks\userLogin.ts
 */
import { ref, reactive, unref } from 'vue';
import { ILogin } from 'type/api.type';
import { router } from './useRouter';
import GlobalPack from 'utils/message/index';
import UserStore from 'store/modules/user';
import { UserLogin } from '@/axios/modules/user';
import WebStorage from 'utils/cache/index';
// import * as Verify from 'utils/verify';
export default function userLogin() {
  const loginInfo = reactive<ILogin>({
    userName: '',
    password: '',
  });
  const loading = ref<Boolean>(false);

  const { handleRouterJump } = router();

  const loginForm = ref<any>(null);

  const loginRules = reactive<any>({
    userName: [
      {
        required: true,
        message: '手机号码不能为空',
      },
      // {
      //   validator: Verify.formValidateGene(
      //     'validateMobile',
      //     '请输入13/4/5/6/7/8/9开头的11位手机号码'
      //   ),
      // },
    ],
    password: [
      { required: true, message: '请输入账号密码', trigger: 'blur' },
      {
        max: 6,
        min: 6,
        message: '密码长度为6位',
      },
    ],
  });
  const handleSubmit = async (): Promise<void> => {
    const valid = await unref(loginForm).validate();
    if (valid) {
      try {
        loading.value = true;
        const { token, userInfo } = await UserLogin(valid);
        UserStore.actionGetUserToken(token);
        UserStore.actionGetUserInfo(userInfo);
        WebStorage.set('token', token);
        WebStorage.set('userInfo', userInfo);
        GlobalPack.message('登录成功，欢迎回来', 'success');
        handleRouterJump({ name: 'index' });
      } finally {
        loading.value = false;
      }
    }
  };
  return {
    loginInfo,
    loginForm,
    loginRules,
    loading,
    handleSubmit,
  };
}
